const dataBase = require('../../mysql')

const sql = require('../../mysql/sql')
const verify = require('../../auth/verify')
const verifyRequestMethod = require('../../tool/verifyRequestMethod')

/**
 * @description 修改个人资料
 */
module.exports = function () {
    const that = this
    const authorization = this.request.headers.authorization
    /**
     * @description 请求验证
     */
    verifyRequestMethod(this.request, 'POST').then(function () {
        /**
         * @description 授权验证
         */
        if (that.isDef(authorization)) {
            return verify(authorization)
        } else {
            return Promise.reject(new Error('缺少Authorization！'))
        }
    }).then(function (data) {
        /**
         * @description 用户名
         * @type {string|string}
         */
        const username = data.username
        /**
         * @description 获取body
         */
        return that.getBodyData(that.request).then(function (data) {
            /**
             * @description 合并数据,防止自定义数据
             */
            return Promise.resolve({ body: data, username: username })
        })
    }).then(function (options) {
        /**
         * @description 获取前端body
         * @type {any}
         */
        const data = options.body
        /**
         * @description 用户名
         * @type {string}
         */
        const username = options.username
        const address = data.address
        const nikeName = data.nikename
        const signature = data.signature
        const cover = data.cover
        const sex = parseInt(data.sex)
        if (!!address && nikeName.length > 300) {
            that.response.outPrintError('请输入正确的地址！')
        } else if (!!nikeName && nikeName.length < 3) {
            that.response.outPrintError('请输入正确的昵称！')
        } else if (!!signature && signature.length < 12) {
            that.response.outPrintError('请输入正确的个性签名！')
        } else if (!!sex && (sex !== 0 || sex !== 1)) {
            that.response.outPrintError('请选择正确的性别！')
        } else if (!cover) {
            that.response.outPrintError('请上传头像！')
        } else if (that.image.isImageSuffix(cover)) {
            that.response.outPrintError('头像不是一张图片！')
        } else {
            return dataBase.connect(sql.SQL_UPDATE_USER_INFO(username, address, nikeName, signature, cover, sex))
        }
    }).then(function () {
        that.response.outPrintData({}, '修改成功！')
    }).catch(function (e) {
        that.response.outPrintError((e && e.message) || '未知错误！')
    })
}